package com.ln.lnzw;

import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseActivity;
import com.ln.lnzw.base.SupportFragment;
import com.ln.lnzw.bean.ImplementationSubjectBean;
import com.ln.lnzw.bean.NewImplementationSubjectBean;
import com.ln.lnzw.fragment.HandleAffairsFragment;
import com.ln.lnzw.fragment.MineFragment;
import com.ln.lnzw.fragment.PublicityFragment;
import com.ln.lnzw.fragment.ServiceFragment;
import com.ln.lnzw.net.HttpMethodString;
import com.ln.lnzw.utils.StatusBarUtil;
import com.ln.lnzw.view.BottomBar;
import com.ln.lnzw.view.BottomBarTab;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {
    @BindView(R.id.contentContainer)
    FrameLayout contentContainer;
    @BindView(R.id.bottomBar)
    BottomBar bottomBar;
    private SupportFragment[] mFragments = new SupportFragment[4];
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        addFragment(savedInstanceState);
        //定位
        initLocation();
        initData();//省市县
        getImplementationSubject();//实施主体
        getTypeAuthority();//职权类型

    }

    private void getTypeAuthority() {
        HttpMethodString.getInstance().info.getStringData(AppConstant.TERMS_REFERENCE_URL)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        activity.spUtils.put(AppConstant.TYPEOFAUTHRITY,s);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void getImplementationSubject() {
        HttpMethodString.getInstance().info.getStringData(AppConstant.IMPLEMENTATION_SUBJECT_URL)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        activity.spUtils.put(AppConstant.IMPLEMENTATION,s);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("666", "onError: "+e.toString());
                    }

                    @Override
                    public void onComplete() {


                    }
                });

    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                       //可在其中解析amapLocation获取相应内容。
                        aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        aMapLocation.getLatitude();//获取纬度
                        aMapLocation.getLongitude();//获取经度
                        aMapLocation.getAccuracy();//获取精度信息
                        aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                        aMapLocation.getCountry();//国家信息
                        aMapLocation.getProvince();//省信息
                        aMapLocation.getCity();//城市信息
                        aMapLocation.getDistrict();//城区信息
                        aMapLocation.getStreet();//街道信息
                        aMapLocation.getStreetNum();//街道门牌号信息
                        aMapLocation.getCityCode();//城市编码
                        aMapLocation.getAdCode();//地区编码
                        Log.i("505", "onLocationChanged:省市---"+"省："+aMapLocation.getProvince()+"--市："+aMapLocation.getCity()+"--县："+aMapLocation.getDistrict());
                        Log.i("505", "onLocationChanged:编码--- "+""+aMapLocation.getCityCode()+"--市："+aMapLocation.getAdCode());
                        Log.i("505", "onLocationChanged: "+aMapLocation.getAccuracy());

                    }else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError","location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });
        AMapLocationClientOption option = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if(null != mLocationClient){
            mLocationClient.setLocationOption(option);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        option.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        option.setOnceLocationLatest(true);
        option.setHttpTimeOut(20000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(option);
        //启动定位
        mLocationClient.startLocation();
//        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
    }

    private void initData() {
        HttpMethodString.getInstance().info.getStringData(AppConstant.CIYT_URL)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        Log.i("090", "onNext: "+s);
                         spUtils.put(AppConstant.JSON_CITY,s);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i("666", "onError: "+e.toString());
                    }

                    @Override
                    public void onComplete() {


                    }
                });
    }

    private void addFragment(Bundle savedInstanceState) {
        StatusBarUtil.setTranslucentForImageViewInFragment(MainActivity.this, 0, null);
        if (savedInstanceState == null) {
            mFragments[0] = HandleAffairsFragment.newInstance();
            mFragments[1] = PublicityFragment.newInstance();
            mFragments[2] = ServiceFragment.newInstance();
            mFragments[3] = MineFragment.newInstance();

            getSupportDelegate().loadMultipleRootFragment(R.id.contentContainer, 0,
                    mFragments[0],
                    mFragments[1],
                    mFragments[2],
                    mFragments[3]);
        } else {
            mFragments[0] = findFragment(HandleAffairsFragment.class);
            mFragments[1] = findFragment(PublicityFragment.class);
            mFragments[2] = findFragment(ServiceFragment.class);
            mFragments[3] = findFragment(MineFragment.class);
        }

        bottomBar.addItem(new BottomBarTab(this, R.mipmap.icon_btn_home_nor,"办事"))
                .addItem(new BottomBarTab(this, R.mipmap.icon_btn_open_nor, "公开"))
                .addItem(new BottomBarTab(this, R.mipmap.icon_btn_service_nor, "服务"))
                .addItem(new BottomBarTab(this, R.mipmap.icon_btn_my_nor, "我的"));
        bottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                Log.i("123", "onTabSelected: "+position+"-----"+prePosition);
                getSupportDelegate().showHideFragment(mFragments[position], mFragments[prePosition]);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });

    }

}
